import java.util.Arrays;

public class 最接近的三数之和 {
    
    public static void main(String[] args) {
        

        
    }

    public static int threeSumClosest(int[] nums, int target) {

        if(null == nums || nums.length < 1) return 0;

        //先排序
        Arrays.sort(nums);

        int sum = nums[0] + nums[1] + nums[2];

        for(int i=0; i<nums.length; i++){

            int left = i+1;
            int right = nums.length - 1;

            while (left < right) {
                
                int preSum = nums[left] + nums[i] + nums[right];

                if(Math.abs(target - preSum) < Math.abs(target - sum)){

                    sum = preSum;
                }

                if(preSum < target){

                    left ++;
                } else if(preSum > target) {

                    right --;

                } else{

                    return sum;
                }
            }
        }


        return sum;
    }
}
